<template>
    <div class="layout-main-conent">
        <a-card
            :bordered="false"
            style="margin-bottom: 15px"
            :bodyStyle="{paddingBottom: '0'}"
        >
            <a-form :labelCol="{ span: 6, offset: 0 }" :wrapper-col="{span:18}">
                <a-row :gutter="16" justify="end">
                    <a-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
                        <a-form-item  label="所属应用：">
                            <a-select 
                                placeholder="请选择" 
                                v-model:value="searchModelRef.appId" 
                                :options = "appList"
                                >
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
                        <a-form-item  label="角色名称：">
                            <a-input placeholder="请输入" v-model:value="searchModelRef.roleName" />
                        </a-form-item>
                    </a-col>
                    <a-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
                        <a-form-item  label="角色编码：">
                            <a-input placeholder="请输入" v-model:value="searchModelRef.roleCode" />
                        </a-form-item>
                    </a-col>
                    <a-col :xs="24" :sm="24" :md="24" :lg="6" :xl="6">
                        <div class="text-align-right" style="padding-bottom: 24px" >
                            <a-button type="primary" @click="searchFormSubmit">查询</a-button>
                            <a-button style="margin-left: 8px" @click="searchResetFields">重置</a-button>
                        </div>
                    </a-col>
                </a-row>
            </a-form>
        </a-card>


        <a-card :bordered="false" class="table-card">
            <template #extra>
                <a-button v-if="searchModelRef.appId" type="primary" @click="() => setCreateFormVisible(true)">新建角色</a-button>
            </template>
            <a-table
                row-key="id"
                :columns="columns"
                :data-source="list"
                :loading="loading"
                :pagination="{
                    ...pagination,
                    onChange: (page) => {
                        getList(page);
                    }
                }"
            >
                <template #action="{ record }">
                    <a-button type="link" @click="() => detailUpdateData(record.id)">编辑</a-button>
                    <a-button type="link" @click="() => authData(record.id)">角色授权</a-button>
                    <a-button type="link" @click="() => openUserManager(record.id)">用户管理</a-button>
                    <a-button type="link" @click="() => deleteTableData(record.id)" class="delete-button">删除</a-button>
                </template>

            </a-table>
        </a-card>
        <create-form 
            :visible="createFormVisible" 
            :onCancel="() => setCreateFormVisible(false)" 
            :onSubmitLoading="createSubmitLoading" 
            :onSubmit="createSubmit"
            :appId="searchModelRef.appId"
        />

        <update-form
            v-if="updateFormVisible"
            :visible="updateFormVisible"
            :values="updateRoleData"
            :onCancel="() => updataFormCancel()"
            :onSubmitLoading="updateSubmitLoading"
            :onSubmit="updateSubmit"
        />
        <role-authorization 
            :visible="authorizationVisible"
            :roleId="roleId"
            :onCancel="() => cancelAuthVisible()"
        />
        <user-manager
            :visible="userManagerVisible"
            :roleId="roleId"
            :onCancel="() => cancelUserVisible()"
        />
    </div>
</template>
<script lang="ts" setup>
import { computed, onMounted, ref, watch } from "vue";
import { useStore } from "vuex";
import { message, Modal, Form } from "ant-design-vue";

import CreateForm from './components/CreateForm.vue';
import UpdateForm from './components/UpdateForm.vue';
import RoleAuthorization from './components/RoleAuthorization.vue';
import { StateType as ListStateType } from "./store";
import { PaginationConfig, TableListItem } from './data';
import { queryList, detailData, queryAppList, createData, updateData, removeData } from './service'
import UserManager from "./components/UserManager.vue";
const store = useStore<{ ListSearchTable: ListStateType}>();
// 角色id
const roleId = ref()
const authorizationVisible = ref(false)
// 授权弹框
const authData = (id: number) => {
    roleId.value = id
    authorizationVisible.value = true
}
const cancelAuthVisible = () => {
    authorizationVisible.value = false
}

// 用户管理
const userManagerVisible = ref(false)
const openUserManager = (id: number) => {
    roleId.value = id
    userManagerVisible.value = true
}
const cancelUserVisible = () => {
    userManagerVisible.value = false
}
 // 列表数据
 const list = computed<TableListItem[]>(() => store.state.ListSearchTable.tableData.list);

// 列表分页
const pagination = computed<PaginationConfig>(() => store.state.ListSearchTable.tableData.pagination);
watch(
    () => pagination.value.pageSize,
    (val) => {
        console.log('dasdasdas', val)
    }
)
// 列表字段
const columns =[
    {
        title: '序号',
        dataIndex: 'index',
        width: 80,
        customRender: ({text, index}: { text: any; index: number}) => (pagination.value.current - 1) * pagination.value.pageSize + index + 1,
    },
    {
        title: '编码',
        dataIndex: 'roleCode'
    },
    {
        title: '角色名称',
        dataIndex: 'roleName',
    },
    {
        title: '公共角色',
        dataIndex: 'publicStatus',
        customRender: ({text}: { text: any}) => {
            return text === '1' ? '是' : '否'
        },
    },
    {
        title: '系统角色',
        dataIndex: 'sysStatus',
        customRender: ({text}: { text: any}) => {
            return text === '1' ? '是' : '否'
        },
    },
    {
        title: '更改日期',
        dataIndex: 'updatedTime'
    },
    {
        title: '状态',
        dataIndex: 'enableStatus',
        key: 'enableStatus',
        slots: { customRender: 'enableStatus' },
    },
    {
        title: '操作',
        key: 'action',
        width: 360,
        slots: { customRender: 'action' },
    },
];

// 获取数据
const loading = ref<boolean>(true);
const getList = async (current: number): Promise<void> => {
    loading.value = true;
    await store.dispatch('ListSearchTable/queryTableData', {
        pageSize: pagination.value.pageSize,
        pageNum: current,
        ...searchModelRef.value
    });
    loading.value = false;
    
}
const appList = ref([])
const getAppList = async (): Promise<void> => {
    const res = await queryAppList();
    if (res.success) {
        if (res.data.length > 0) {
            res.data.forEach(ele => {
                const obj = {
                    label: ele.name,
                    value: ele.id + ''
                }
                appList.value.push(obj)
            })
            searchModelRef.value.appId = res.data[0].id + ''
            getList(1)
        }
    }
}
// 表单值
const searchModelRef = ref({
    appId: '',
    roleCode: '',
    roleName: ''
});
// 搜索
const searchFormSubmit = async () => {
    getList(1)
}
const searchResetFields = async() => {
    searchModelRef.value = ({
        roleCode: '',
        roleName: '',
        appId: searchModelRef.value.appId
    })
    searchFormSubmit()
}
// 新增弹框 - visible
const createFormVisible = ref<boolean>(false);
const setCreateFormVisible = (val: boolean) => {
    createFormVisible.value = val;
};
// 新增弹框 - 提交 loading
const createSubmitLoading = ref<boolean>(false);
// 新增弹框 - 提交
const createSubmit = async (values: Omit<TableListItem, 'id'>) => {
    createSubmitLoading.value = true;
    const res = await createData(values);
    if(res.success) {
        setCreateFormVisible(false);
        message.success('新增成功！');
        getList(1);
    }
    createSubmitLoading.value = false;
}
// 编辑弹框 data
const updateRoleData = ref({});
const detailUpdateData = async (id: any) => {
    const params = {
        id: id
    }
    const res = await detailData(params);
    if(res.success) {
        updateRoleData.value = res.data
        setUpdateFormVisible(true);
    }
}
// 编辑弹框 - visible
const updateFormVisible = ref<boolean>(false);
const setUpdateFormVisible = (val: boolean) => {
    updateFormVisible.value = val;
}
const updataFormCancel = () => {
    setUpdateFormVisible(false);
    store.commit('ListSearchTable/setUpdateData',{});
}
// 编辑弹框 - 提交 loading
const updateSubmitLoading = ref<boolean>(false);
// 编辑弹框 - 提交
const updateSubmit = async (values: TableListItem) => {
    updateSubmitLoading.value = true;
    const res = await updateData(values);
    if(res.success) {
        updataFormCancel();                
        message.success('编辑成功！');
        getList(pagination.value.current);
    }
    updateSubmitLoading.value = false;
}
const deleteVisible = ref(false)
// 删除
const deleteTableData = (id: number) => {
    Modal.confirm({
        title: '删除',
        content: '确定删除吗？',
        okText: '确认',
        cancelText: '取消',
        onOk: async () => {
            const ids = [id]
            const res = await removeData(ids)
            if (res.success) {
                message.success('删除成功！');
                getList(pagination.value.current);
            }
        }
    });
}
// type Key = string | number;

// const state = reactive<{
//     selectedRowKeys: Key[];
//     loading: boolean;
// }>({
//     selectedRowKeys: [], // Check here to configure the default column
//     loading: false,
// });
// const onSelectChange = (selectedRowKeys: Key[], selectedRows: object[]) => {
//     console.log('selectedRowKeys changed: ', selectedRowKeys);
//     console.log('selectedRows changed: ', selectedRows);
//     state.selectedRowKeys = selectedRowKeys;
// };

onMounted(()=> {
    getAppList()
})
</script>
<style scoped lang="less">
.delete-button{
    color: red;
}
.role-manager{
    margin-right: 20px;
}
.table-card{
  :deep(.ant-card-body){
    padding: 0px 24px 24px 24px;
  }
}
:deep(.ant-card-head){
    border: none;
}
</style>